package com.zhentao.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.zhentao.pojo.Order;
import com.zhentao.pojo.Product;
import com.zhentao.service.OrderService;
import com.zhentao.service.ProductService;
import com.zhentao.util.ProductPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/productpay")
public class ProductPayController {
    @Autowired
    private ProductPayUtil productPayUtil;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    
    // 存储订单号与订单ID的映射关系
    private static final Map<String, Long> orderMapping = new java.util.concurrent.ConcurrentHashMap<>();

    @PostMapping("/pay")
    public Map<String, Object> alipay(@RequestHeader String token, @RequestBody Order orderModel) throws AlipayApiException {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证订单是否存在
            Order order = orderService.getById(orderModel.getId());
            if (order == null) {
                result.put("code", 400);
                result.put("message", "订单不存在");
                return result;
            }
            
            // 检查订单状态
            if (order.getStatus() != null && order.getStatus().equals("paid")) {
                result.put("code", 400);
                result.put("message", "订单已支付");
                return result;
            }
            
            // 获取产品信息
            Product product = productService.getById(Long.valueOf(order.getProductid()));
            if (product == null) {
                result.put("code", 400);
                result.put("message", "产品不存在");
                return result;
            }
            
            // 生成订单号
            String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            String OrderNum = time + user;
            
            // 存储订单号与订单ID的映射关系
            orderMapping.put(OrderNum, order.getId());
            
            float orderValue = order.getPayAmount().floatValue();
            String subject = product.getName();
            
            // 生成支付链接
            String paymentUrl = productPayUtil.generatePaymentUrl(OrderNum, orderValue, subject);
            
            if (paymentUrl != null && !paymentUrl.isEmpty()) {
                result.put("code", 200);
                result.put("message", "支付链接生成成功");
                result.put("orderNo", OrderNum);
                result.put("amount", orderValue);
                result.put("subject", subject);
                result.put("paymentUrl", paymentUrl);
            } else {
                result.put("code", 500);
                result.put("message", "支付链接生成失败");
            }
            
        } catch (Exception e) {
            System.err.println("支付请求处理异常: " + e.getMessage());
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "支付请求处理失败: " + e.getMessage());
        }
        
        return result;
    }

    // 支付回调处理
    @GetMapping("/toSuccess")
    public String returns(String out_trade_no) throws ParseException {
        try {
            System.out.println("支付回调，订单号: " + out_trade_no);
            
            String query = productPayUtil.query(out_trade_no);
            System.out.println("支付宝查询结果: " + query);
            
            JSONObject jsonObject = JSONObject.parseObject(query);
            Object o = jsonObject.get("alipay_trade_query_response");
            Map map = (Map) o;
            System.out.println("查询响应: " + map);
            
            Object s = map.get("trade_status");
            if (s != null && s.equals("TRADE_SUCCESS")) {
                System.out.println("订单支付成功，开始更新订单状态");
                this.updateOrderStatus(out_trade_no);
                System.out.println("订单状态更新完成");
                return "redirect:http://localhost:8081/#/paysuccess";
            } else {
                System.out.println("订单支付失败，状态: " + s);
                return "redirect:http://localhost:8081/#/payfail";
            }
        } catch (Exception e) {
            System.err.println("支付回调处理异常: " + e.getMessage());
            e.printStackTrace();
            return "redirect:http://localhost:8081/#/payfail";
        }
    }
    
    // 直接密码支付接口
    @PostMapping("/passwordPay")
    public Map<String, Object> passwordPay(@RequestHeader String token, @RequestBody Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取请求参数
            Long orderId = Long.valueOf(requestData.get("orderId").toString());
            String paymentPassword = requestData.get("paymentPassword").toString();
            
            System.out.println("密码支付请求，订单ID: " + orderId + ", 支付密码长度: " + paymentPassword.length());
            
            // 验证订单是否存在
            Order order = orderService.getById(orderId);
            if (order == null) {
                result.put("code", 400);
                result.put("message", "订单不存在");
                return result;
            }
            
            // 检查订单状态
            if (order.getStatus() != null && order.getStatus().equals("paid")) {
                result.put("code", 400);
                result.put("message", "订单已支付");
                return result;
            }
            
            // 验证支付密码格式
            if (paymentPassword == null || paymentPassword.length() != 6) {
                result.put("code", 400);
                result.put("message", "支付密码格式错误");
                return result;
            }
            
            // 获取产品信息
            Product product = productService.getById(Long.valueOf(order.getProductid()));
            if (product == null) {
                result.put("code", 400);
                result.put("message", "产品不存在");
                return result;
            }
            
            // 生成订单号
            String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();
            String OrderNum = time + user;
            
            // 存储订单号与订单ID的映射关系
            orderMapping.put(OrderNum, order.getId());
            
            // 直接完成支付（模拟支付成功）
            System.out.println("密码支付验证通过，开始更新订单状态");
            
            // 更新订单状态为已支付
            order.setStatus("paid");
            order.setPayTime(new Date());
            orderService.updateById(order);
            
            // 更新产品销量
            updateProductSales(Long.valueOf(order.getProductid()));
            
            // 清除映射关系
            orderMapping.remove(OrderNum);
            
            result.put("code", 200);
            result.put("message", "支付成功");
            result.put("orderNo", OrderNum);
            result.put("amount", order.getPayAmount());
            result.put("subject", product.getName());
            result.put("status", "paid");
            
            System.out.println("密码支付完成，订单 " + order.getId() + " 状态已更新为已支付");
            
        } catch (Exception e) {
            System.err.println("密码支付异常: " + e.getMessage());
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "支付失败: " + e.getMessage());
        }
        
        return result;
    }

    // 检查支付状态
    @GetMapping("/checkPaymentStatus")
    public Map<String, Object> checkPaymentStatus(@RequestParam String orderNo) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            System.out.println("检查支付状态，订单号: " + orderNo);
            
            String query = productPayUtil.query(orderNo);
            System.out.println("支付宝查询结果: " + query);
            
            JSONObject jsonObject = JSONObject.parseObject(query);
            Object o = jsonObject.get("alipay_trade_query_response");
            Map map = (Map) o;
            System.out.println("查询响应: " + map);
            
            Object tradeStatus = map.get("trade_status");
            if (tradeStatus != null && tradeStatus.equals("TRADE_SUCCESS")) {
                System.out.println("检测到支付成功，开始更新订单状态");
                this.updateOrderStatus(orderNo);
                
                result.put("code", 200);
                result.put("message", "支付成功");
                result.put("status", "paid");
            } else {
                result.put("code", 200);
                result.put("message", "未支付");
                result.put("status", "unpaid");
            }
            
        } catch (Exception e) {
            System.err.println("检查支付状态异常: " + e.getMessage());
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "检查支付状态失败: " + e.getMessage());
        }
        
        return result;
    }
    
    // 更新订单状态
    private void updateOrderStatus(String outTradeNo) {
        try {
            System.out.println("开始更新订单状态，订单号: " + outTradeNo);
            
            Long orderId = orderMapping.get(outTradeNo);
            
            if (orderId != null) {
                Order order = orderService.getById(orderId);
                
                if (order != null && "pending".equals(order.getStatus())) {
                    order.setStatus("paid");
                    order.setPayTime(new Date());
                    orderService.updateById(order);
                    
                    updateProductSales(Long.valueOf(order.getProductid()));
                    orderMapping.remove(outTradeNo);
                    
                    System.out.println("订单 " + order.getId() + " 状态已更新为已支付");
                } else {
                    System.out.println("订单不存在或已支付: " + orderId);
                }
            } else {
                System.out.println("未找到订单号对应的订单ID: " + outTradeNo);
                // 如果映射中没有找到，尝试通过订单号直接查找
                try {
                    Order order = orderService.getOne(
                        new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Order>()
                            .eq("orderNo", outTradeNo)
                    );
                    
                    if (order != null && "pending".equals(order.getStatus())) {
                        order.setStatus("paid");
                        order.setPayTime(new Date());
                        orderService.updateById(order);
                        updateProductSales(Long.valueOf(order.getProductid()));
                        System.out.println("通过订单号直接查找并更新订单状态成功");
                    }
                } catch (Exception e) {
                    System.err.println("通过订单号直接查找订单失败: " + e.getMessage());
                }
            }
            
        } catch (Exception e) {
            System.err.println("更新订单状态异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 更新产品销量
    private void updateProductSales(Long productId) {
        try {
            Product product = productService.getById(productId);
            
            if (product != null) {
                Integer currentSales = product.getSales() != null ? product.getSales() : 0;
                product.setSales(currentSales + 1);
                
                Integer currentStock = product.getStock() != null ? product.getStock() : 0;
                if (currentStock > 0) {
                    product.setStock(currentStock - 1);
                }
                
                productService.updateById(product);
                System.out.println("产品 " + productId + " 销量已更新");
            }
        } catch (Exception e) {
            System.err.println("更新产品销量异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
